package com.phiture.erp.stock.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.MPJLambdaWrapperX;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.phiture.erp.basic.api.pojo.resp.ErpMaterialResp;
import com.phiture.erp.basic.api.service.ErpMaterialApi;
import com.phiture.erp.basic.api.service.ErpSupplierApi;
import com.phiture.erp.common.constants.ErpNoPrefixConstants;
import com.phiture.erp.common.enums.ErpAuditStatus;
import com.phiture.erp.common.enums.ErpStockRecordBizTypeEnum;
import com.phiture.erp.common.utils.ErpNoGenerator;
import com.phiture.erp.stock.core.pojo.dto.ErpStockInPageReqDTO;
import com.phiture.erp.stock.core.pojo.dto.ErpStockInSaveReqDTO;
import com.phiture.erp.stock.core.pojo.dto.ErpStockRecordCreateReqDTO;
import com.phiture.erp.stock.core.service.ErpStockInService;
import com.phiture.erp.stock.core.service.ErpStockRecordService;
import com.phiture.erp.stock.core.service.ErpWarehouseService;
import com.phiture.erp.stock.dal.entity.ErpStockInDO;
import com.phiture.erp.stock.dal.entity.ErpStockInItemDO;
import com.phiture.erp.stock.dal.mapper.ErpStockInItemMapper;
import com.phiture.erp.stock.dal.mapper.ErpStockInMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static com.phiture.erp.common.constants.ErrorCodeConstants.*;

/**
 * @author YH
 * @date 2025/4/13
 */

@Service
@RequiredArgsConstructor
public class ErpStockInServiceImpl implements ErpStockInService {
    private final ErpStockInMapper stockInMapper;
    private final ErpMaterialApi materialApi;
    private final ErpStockInItemMapper stockInItemMapper;
    private final ErpWarehouseService warehouseService;
    private final ErpNoGenerator erpNoGenerator;
    private final ErpSupplierApi supplierApi;
    private final ErpStockRecordService stockRecordService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createStockIn(ErpStockInSaveReqDTO createReqDTO) {
        // 1.1 校验入库项的有效性
        List<ErpStockInItemDO> stockInItems = validateStockInItems(createReqDTO.getItems());
        // 1.2 校验供应商
        supplierApi.validateSupplier(createReqDTO.getSupplierId());
        // 1.3 生成入库单号，并校验唯一性
        String orderNo = erpNoGenerator.generate(ErpNoPrefixConstants.STOCK_IN_NO_PREFIX);
        validateOrderNo(orderNo);

        // 2.1 插入入库单
        ErpStockInDO stockIn = BeanUtils.toBean(createReqDTO, ErpStockInDO.class, in -> in
                .setNo(orderNo).setStatus(ErpAuditStatus.PROCESS.getStatus())
                .setTotalCount(getSumValue(stockInItems, ErpStockInItemDO::getCount, BigDecimal::add))
                .setTotalPrice(getSumValue(stockInItems, ErpStockInItemDO::getTotalPrice, BigDecimal::add, BigDecimal.ZERO)));
        stockInMapper.insert(stockIn);
        // 2.2 插入入库单项
        stockInItems.forEach(o -> o.setInId(stockIn.getId()));
        stockInItemMapper.insertBatch(stockInItems);
        return stockIn.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStockIn(ErpStockInSaveReqDTO updateReqDTO) {
        // 1.1 校验存在
        ErpStockInDO stockIn = validateStockInExists(updateReqDTO.getId());
        if (ErpAuditStatus.APPROVE.getStatus().equals(stockIn.getStatus())) {
            throw exception(STOCK_IN_UPDATE_FAIL_APPROVE, stockIn.getNo());
        }
        // 1.2 校验供应商
        supplierApi.validateSupplier(updateReqDTO.getSupplierId());
        // 1.3 校验入库项的有效性
        List<ErpStockInItemDO> stockInItems = validateStockInItems(updateReqDTO.getItems());

        // 2.1 更新入库单
        ErpStockInDO updateObj = BeanUtils.toBean(updateReqDTO, ErpStockInDO.class, in -> in
                .setTotalCount(getSumValue(stockInItems, ErpStockInItemDO::getCount, BigDecimal::add))
                .setTotalPrice(getSumValue(stockInItems, ErpStockInItemDO::getTotalPrice, BigDecimal::add)));
        stockInMapper.updateById(updateObj);
        // 2.2 更新入库单项
        updateStockInItemList(updateReqDTO.getId(), stockInItems);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStockInStatus(Long id, Integer status) {
        boolean approve = ErpAuditStatus.APPROVE.getStatus().equals(status);
        // 1.1 校验存在
        ErpStockInDO stockIn = validateStockInExists(id);
        // 1.2 校验状态
        if (stockIn.getStatus().equals(status)) {
            throw exception(approve ? STOCK_IN_APPROVE_FAIL : STOCK_IN_PROCESS_FAIL);
        }

        // 2. 更新状态
        int updateCount = stockInMapper.updateByIdAndStatus(id, stockIn.getStatus(),
                new ErpStockInDO().setStatus(status));
        if (updateCount == 0) {
            throw exception(approve ? STOCK_IN_APPROVE_FAIL : STOCK_IN_PROCESS_FAIL);
        }

        // 3. 变更库存
        List<ErpStockInItemDO> stockInItems = stockInItemMapper.selectListByInId(id);
        Integer bizType = approve ? ErpStockRecordBizTypeEnum.OTHER_IN.getType()
                : ErpStockRecordBizTypeEnum.OTHER_IN_CANCEL.getType();
        stockInItems.forEach(stockInItem -> {
            BigDecimal count = approve ? stockInItem.getCount() : stockInItem.getCount().negate();
            stockRecordService.createStockRecord(new ErpStockRecordCreateReqDTO(
                    stockInItem.getMaterialId(), stockInItem.getWarehouseId(), count,
                    bizType, stockInItem.getInId(), stockInItem.getId(), stockIn.getNo()));
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteStockIn(List<Long> ids) {
        // 1. 校验不处于已审批
        List<ErpStockInDO> stockIns = stockInMapper.selectBatchIds(ids);
        if (CollUtil.isEmpty(stockIns)) {
            return;
        }
        stockIns.forEach(stockIn -> {
            if (ErpAuditStatus.APPROVE.getStatus().equals(stockIn.getStatus())) {
                throw exception(STOCK_IN_DELETE_FAIL_APPROVE, stockIn.getNo());
            }
        });

        // 2. 遍历删除，并记录操作日志
        stockIns.forEach(stockIn -> {
            // 2.1 删除入库单
            stockInMapper.deleteById(stockIn.getId());
            // 2.2 删除入库单项
            stockInItemMapper.deleteByInId(stockIn.getId());
        });
    }

    @Override
    public ErpStockInDO getStockIn(Long id) {
        return stockInMapper.selectById(id);    }

    @Override
    public PageResult<ErpStockInDO> getStockInPage(ErpStockInPageReqDTO pageReqDTO) {
         MPJLambdaWrapperX<ErpStockInDO> query = new MPJLambdaWrapperX<ErpStockInDO>()
                .likeIfPresent(ErpStockInDO::getNo, pageReqDTO.getNo())
                .eqIfPresent(ErpStockInDO::getSupplierId, pageReqDTO.getSupplierId())
                .betweenIfPresent(ErpStockInDO::getInTime, pageReqDTO.getInTime())
                .eqIfPresent(ErpStockInDO::getStatus, pageReqDTO.getStatus())
                .likeIfPresent(ErpStockInDO::getRemark, pageReqDTO.getRemark())
                .eqIfPresent(ErpStockInDO::getCreator, pageReqDTO.getCreator())
                .orderByDesc(ErpStockInDO::getId);
        if (pageReqDTO.getWarehouseId() != null || pageReqDTO.getMaterialId() != null) {
            query.leftJoin(ErpStockInItemDO.class, ErpStockInItemDO::getInId, ErpStockInDO::getId)
                    .eq(pageReqDTO.getWarehouseId() != null, ErpStockInItemDO::getWarehouseId, pageReqDTO.getWarehouseId())
                    .eq(pageReqDTO.getMaterialId() != null, ErpStockInItemDO::getMaterialId, pageReqDTO.getMaterialId())
                    .groupBy(ErpStockInDO::getId); // 避免 1 对多查询，产生相同的 1
        }
        return stockInMapper.selectJoinPage(pageReqDTO, ErpStockInDO.class, query);
    }

    @Override
    public List<ErpStockInItemDO> getStockInItemListByInId(Long inId) {
        return stockInItemMapper.selectListByInId(inId);
    }

    @Override
    public List<ErpStockInItemDO> getStockInItemListByInIds(Collection<Long> inIds) {
        return CollUtil.isEmpty(inIds) ? Collections.emptyList() : stockInItemMapper.selectListByInIds(inIds);
    }

    private List<ErpStockInItemDO> validateStockInItems(List<ErpStockInSaveReqDTO.Item> list) {
        // 1.1 校验产品存在
        List<ErpMaterialResp> materialList = materialApi.validMaterialList(
                convertSet(list, ErpStockInSaveReqDTO.Item::getMaterialId));
        Map<Long, ErpMaterialResp> materialMap = convertMap(materialList, ErpMaterialResp::getId);
        // 1.2 校验仓库存在
        warehouseService.validWarehouseList(convertSet(
                list, ErpStockInSaveReqDTO.Item::getWarehouseId));
        // 2. 转化为 ErpStockInItemDO 列表
        return convertList(list, o -> BeanUtils.toBean(o, ErpStockInItemDO.class, item -> item
                .setMaterialUnitId(materialMap.get(item.getMaterialId()).getUnitId())
                .setTotalPrice(MoneyUtils.priceMultiply(item.getMaterialPrice(), item.getCount()))));
    }

    private void validateOrderNo(String orderNo){
        boolean exists = stockInMapper.exists(
                Wrappers.lambdaQuery(ErpStockInDO.class)
                        .eq(ErpStockInDO::getNo, orderNo)
                        .eq(ErpStockInDO::getDeleted, Boolean.FALSE)
        );
        if(exists){
            throw exception(STOCK_IN_NO_EXISTS);
        }
    }

    private ErpStockInDO validateStockInExists(Long id) {
        ErpStockInDO stockIn = stockInMapper.selectById(id);
        if (stockIn == null) {
            throw exception(STOCK_IN_NOT_EXISTS);
        }
        return stockIn;
    }

    private void updateStockInItemList(Long id, List<ErpStockInItemDO> newList) {
        // 第一步，对比新老数据，获得添加、修改、删除的列表
        List<ErpStockInItemDO> oldList = stockInItemMapper.selectListByInId(id);
        List<List<ErpStockInItemDO>> diffList = diffList(oldList, newList, // id 不同，就认为是不同的记录
                (oldVal, newVal) -> oldVal.getId().equals(newVal.getId()));

        // 第二步，批量添加、修改、删除
        if (CollUtil.isNotEmpty(diffList.get(0))) {
            diffList.get(0).forEach(o -> o.setInId(id));
            stockInItemMapper.insertBatch(diffList.get(0));
        }
        if (CollUtil.isNotEmpty(diffList.get(1))) {
            stockInItemMapper.updateBatch(diffList.get(1));
        }
        if (CollUtil.isNotEmpty(diffList.get(2))) {
            stockInItemMapper.deleteBatchIds(convertList(diffList.get(2), ErpStockInItemDO::getId));
        }
    }
}
